/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.areaDataAll.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.areaDataAll.domain.AreaDataAll;
import com.fzhucc.modules.areaDataAll.domain.dto.AreaDataAllQueryCriteria2;
import com.fzhucc.modules.dataOrg.domain.DataOrg;
import com.fzhucc.modules.dataOrg.repository.DataOrgRepository;
import com.fzhucc.modules.notice.repository.NoticeRepository;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoRepository;
import com.fzhucc.modules.sciStudio.repository.SciStudioRepository;
import com.fzhucc.modules.sciTdStatusLog.repository.SciTechnologyDemandPpLogRepository;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemand;
import com.fzhucc.modules.sciTechnologyDemand.repository.SciTechnologyDemandRepository;
import com.fzhucc.modules.ts.repository.TsTeamRepository;
import com.fzhucc.utils.ValidationUtil;
import com.fzhucc.utils.FileUtil;
import com.fzhucc.utils.PageUtil;
import com.fzhucc.utils.QueryHelp;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.areaDataAll.repository.AreaDataAllRepository;
import com.fzhucc.modules.areaDataAll.domain.dto.AreaDataAllDto;
import com.fzhucc.modules.areaDataAll.domain.dto.AreaDataAllQueryCriteria;
import com.fzhucc.modules.areaDataAll.service.mapstruct.AreaDataAllMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-04-01
 **/
@Service
@RequiredArgsConstructor
public class AreaDataAllService {

    @Value("${sci.audit.shtg}")
    public String shtg;

    private final AreaDataAllRepository areaDataAllRepository;

    private final SciTechnologyDemandPpLogRepository sciTechnologyDemandPpLogRepository;

    private final SciStudioRepository sciStudioRepository;

    private final NoticeRepository noticeRepository;

    private final SciTechnologyDemandRepository sciTechnologyDemandRepository;

    private final SciPersonnelInfoRepository sciPersonnelInfoRepository;

    private final TsTeamRepository tsTeamRepository;

    private final DataOrgRepository dataOrgRepository;
    private final AreaDataAllMapper areaDataAllMapper;

    public Map<String, Object> queryAll(AreaDataAllQueryCriteria criteria, Pageable pageable) {
        Page<AreaDataAll> page = areaDataAllRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(areaDataAllMapper::toDto));
    }

    public List<AreaDataAllDto> queryAll(AreaDataAllQueryCriteria criteria) {
        return areaDataAllMapper.toDto(areaDataAllRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public AreaDataAllDto findById(Integer id) {
        AreaDataAll areaDataAll = areaDataAllRepository.findById(id).orElseGet(AreaDataAll::new);
        ValidationUtil.isNull(areaDataAll.getId(), "AreaDataAll", "id", id);
        return areaDataAllMapper.toDto(areaDataAll);
    }

    @Transactional(rollbackFor = Exception.class)
    public AreaDataAllDto create(AreaDataAll resources) {
        return areaDataAllMapper.toDto(areaDataAllRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(AreaDataAll resources) {
        AreaDataAll areaDataAll = areaDataAllRepository.findById(resources.getId()).orElseGet(AreaDataAll::new);
        ValidationUtil.isNull(areaDataAll.getId(), "AreaDataAll", "id", resources.getId());
        areaDataAll.copy(resources);
        areaDataAllRepository.save(areaDataAll);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            areaDataAllRepository.deleteById(id);
        }
    }

    public void download(List<AreaDataAllDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AreaDataAllDto areaDataAll : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("地区", areaDataAll.getOrgArea());
            map.put("日期", areaDataAll.getDay());
            map.put("劳模截止日已审核通过数", areaDataAll.getLmSh());
            map.put("劳模截止日未审核通过数", areaDataAll.getLmWsh());
            map.put("需求截止日已审核通过数", areaDataAll.getXqSh());
            map.put("需求截止日未审核通过数", areaDataAll.getXqwSh());
            map.put("工作室截止日已审核通过数", areaDataAll.getStudioSh());
            map.put("工作室截止日未审核通过数", areaDataAll.getStudioWsh());
            map.put("技术服务队截止日已审核通过数", areaDataAll.getTsSh());
            map.put("技术服务队截止日未审核通过数", areaDataAll.getTsWsh());
            map.put("需求截止日已匹配总数", areaDataAll.getXqYpp());
            map.put("需求截止日已解决总数", areaDataAll.getXqYjj());
            map.put("资讯截止日总数", areaDataAll.getZx());
            map.put("日期具体值", areaDataAll.getMyDay());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    public List<AreaDataAllDto> queryAllByDayData(AreaDataAllQueryCriteria2 criteria) throws ParseException {
        // 定义日期格式
        String day = criteria.getDay();
        if (day == null) {
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 将LocalDate转换为指定格式的字符串
            String formattedDate = currentDate.format(formatter);
            day = formattedDate;
        }
        if (!day.contains("-")) {
            throw new BadRequestException("请输入正确的时间");
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date myDate = formatter.parse(day);

        List<AreaDataAllDto> list = new ArrayList<AreaDataAllDto>();
        List<DataOrg> dataOrgs = dataOrgRepository.queryByOrgAreaLike("%福州市%", "福建省;", "福建省;福建省总工会（本级）;");
        //所有符合的福州市org
        if (dataOrgs != null && dataOrgs.size() > 0) {
            for (DataOrg org : dataOrgs) {
                String org1 = org.getOrg();
                AreaDataAllDto areaDataAllDto = scaleData(myDate, org1, day);
                list.add(areaDataAllDto);
            }
        }
        return list;
    }

    public AreaDataAllDto scaleData(Date myDate, String org, String dateStr) {
        int lmSh = 0;
        int lmWsh = 0;
        int xqSh = 0;
        int xqWsh = 0;
        int studioSh = 0;
        int studioWsh = 0;
        int tsSh = 0;
        int tsWsh = 0;
        int zx = 0;
        int yipipei = 0;
        int yijiejue = 0;
        lmSh = sciPersonnelInfoRepository.findNormalByLikeAreaWithOutIsShowCSevenCreateLikeDshWithOutS("%" + org + "%", "%审核通过%", myDate);
        lmWsh = sciPersonnelInfoRepository.findNormalByLikeAreaWithOutIsShowCSevenCreateLikeDshWithOutSNotLike("%" + org + "%", "%审核通过%", myDate);
        xqSh = sciTechnologyDemandRepository.findNormalByLikeAreaWithOutIsShowCSevenCreateLikeDshWithOutS("%" + org + "%", "%审核通过%", myDate);
        xqWsh = sciTechnologyDemandRepository.findNormalByLikeAreaWithOutIsShowCSevenCreateLikeDshWithOutSNotLike("%" + org + "%", "%审核通过%", myDate);
        studioSh = sciStudioRepository.findNormalByLikeAreaWithOutIsShowCSevenCreateLikeDshWithOutS("%" + org + "%", "%审核通过%", myDate);
        studioWsh = sciStudioRepository.findNormalByLikeAreaWithOutIsShowCSevenCreateLikeDshWithOutSNotLike("%" + org + "%", "%审核通过%", myDate);
        tsSh = tsTeamRepository.findNormalByLikeAreaWithOutIsShowCSevenCreateLikeDshWithOutS("%" + org + "%", "%审核通过%", myDate);
        tsWsh = tsTeamRepository.findNormalByLikeAreaWithOutIsShowCSevenCreateLikeDshWithOutSNotLike("%" + org + "%", "%审核通过%", myDate);
        zx = noticeRepository.findCountNormalByLikeAreaWithTime("%" + org + "%", myDate);


        //TODO 查询所有需求状态正常 切审核通过  切like 地区
        List<SciTechnologyDemand> listNormal = sciTechnologyDemandRepository.findNormalByLikeAreaWithOutIsShow("%" + org + "%", shtg);
        if (listNormal != null && listNormal.size() > 0) {
            for (SciTechnologyDemand sciTechnologyDemand : listNormal) {
                int c1 = sciTechnologyDemandPpLogRepository.findNormalByTime(sciTechnologyDemand.getId(), "%已匹配%", myDate);
                int c2 = sciTechnologyDemandPpLogRepository.findNormalByTime(sciTechnologyDemand.getId(), "%已解决%", myDate);
                yipipei = yipipei + c1;
                yijiejue = yijiejue + c2;
            }
        }


        AreaDataAllDto dto = new AreaDataAllDto();
        dto.setOrgArea(org);
        dto.setDay(dateStr);
        dto.setLmSh(lmSh);
        dto.setLmWsh(lmWsh);
        dto.setXqSh(xqSh);
        dto.setXqwSh(xqWsh);
        dto.setStudioSh(studioSh);
        dto.setStudioWsh(studioWsh);
        dto.setTsSh(tsSh);
        dto.setTsWsh(tsWsh);
        dto.setZx(zx);
        dto.setXqYpp(yipipei);
        dto.setXqYjj(yijiejue);
        return dto;
    }

    public void downloadByDay(List<AreaDataAllDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AreaDataAllDto areaDataAll : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("隶属", areaDataAll.getOrgArea());
            map.put("截止日期", areaDataAll.getDay());
            map.put("劳模工匠已录入平台审核通过数（个）", areaDataAll.getLmSh());
            map.put("劳模工匠已录入未审核通过（个）", areaDataAll.getLmWsh());
            map.put("征求企业需求数已录入平台审核通过数（个）", areaDataAll.getXqSh());
            map.put("征求企业需求数已录入未审核通过（个）", areaDataAll.getXqwSh());
            map.put("创新工作室已录入平台审核通过数（个）", areaDataAll.getStudioSh());
            map.put("创新工作室已录入未审核通过（个）", areaDataAll.getStudioWsh());
            map.put("技术服务队已录入平台审核通过数（个）", areaDataAll.getTsSh());
            map.put("技术服务队已录入未审核通过（个）", areaDataAll.getTsWsh());
            map.put("解决情况已匹配", areaDataAll.getXqYpp());
            map.put("解决情况已解决", areaDataAll.getXqYjj());
            map.put("发布资讯", areaDataAll.getZx());
            //map.put("日期具体值", areaDataAll.getMyDay());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}